//
//  ToolNet.m
//
//  Created by suyibaishan on 15/8/26.
//  Copyright (c) 2015年 suyibaishan. All rights reserved.
//

#import "ToolNet.h"
#import "UIImageView+WebCache.h"
#import "MRProgressOverlayView+AFNetworking.h"
#import "TSMessage+Category.h"

@interface ToolNet ()

+ (NSURL *)APIBaseURL;

@end

@implementation ToolNet


#pragma mark - 业务请求

-(NSURLSessionDataTask *)getVerifyCode:(NSString *)mobile type:(NSInteger)type url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (mobile && mobile.length) {
        parm[@"mobile"] = mobile;
    }
    parm[@"type"] = [NSNumber numberWithInteger:type];
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

-(NSURLSessionDataTask *)registerApp:(NSString *)mobile password:(NSString *)password vaidCode:(NSString *)vaidCode refereeMobile:(NSString *)refereeMobile url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (mobile && mobile.length) {
        parm[@"mobile"] = mobile;
    }
    if (password && password.length) {
        parm[@"password"] = password;
    }
    if (vaidCode && vaidCode.length) {
        parm[@"vaidCode"] = vaidCode;
    }
    if (refereeMobile && refereeMobile.length) {
        parm[@"refereeMobile"] = refereeMobile;
    }
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

-(NSURLSessionDataTask *)applyForMember:(NSString *)userCode card:(NSString *)card frontCardImg:(NSString *)frontCardImg backCardImg:(NSString *)backCardImg address:(NSString *)address realName:(NSString *)realName url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock;
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (userCode && userCode.length) {
        parm[@"userCode"] = userCode;
    }
    if (card && card.length) {
        parm[@"card"] = card;
    }
    if (frontCardImg && frontCardImg.length) {
        parm[@"frontCardImg"] = frontCardImg;
    }
    if (backCardImg && backCardImg.length) {
        parm[@"backCardImg"] = backCardImg;
    }
    if (address && address.length) {
        parm[@"address"] = address;
    }
    if (realName && realName.length) {
        parm[@"realName"] = realName;
    }
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

-(NSURLSessionDataTask *)forgetPwd:(NSString *)mobile password:(NSString *)password vaidCode:(NSString *)vaidCode url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (mobile && mobile.length) {
        parm[@"mobile"] = mobile;
    }
    if (password && password.length) {
        parm[@"password"] = password;
    }
    if (vaidCode && vaidCode.length) {
        parm[@"vaidCode"] = vaidCode;
    }
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

-(NSURLSessionDataTask *)payCheck:(NSString *)userCode payMethod:(NSString *)payMethod url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (userCode && userCode.length) {
        parm[@"userCode"] = userCode;
    }
    if (payMethod && payMethod.length) {
        parm[@"payMethod"] = payMethod;
    }
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

-(NSURLSessionDataTask *)getBannerList:(NSInteger)type url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    parm[@"type"] = [NSNumber numberWithInteger:type];
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

-(NSURLSessionDataTask *)getCarsList:(NSString *)productName pageNum:(NSInteger)pageNum pageSize:(NSInteger)pageSize url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock;
{
   return  [self getCarsList:productName pageNum:pageNum pageSize:pageSize type:@"1" url:url completionHandler:completionBlock];
}

- (NSURLSessionDataTask *)getCarsList:(NSString *)productName pageNum:(NSInteger)pageNum pageSize:(NSInteger)pageSize type:(NSString *)type url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (productName && productName.length) {
        parm[@"productName"] = productName;
    }
    parm[@"type"] = type;
    parm[@"pageNum"] = [NSNumber numberWithInteger:pageNum];
    parm[@"pageSize"] = [NSNumber numberWithInteger:pageSize];
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

-(NSURLSessionDataTask *)getAnnouncementList:(NSString *)userCode accessToken:(NSString *)accessToken pageNum:(NSInteger)pageNum pageSize:(NSInteger)pageSize url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (userCode && userCode.length) {
        parm[@"userCode"] = userCode;
    }
    if (accessToken && accessToken.length) {
        parm[@"accessToken"] = accessToken;
    }
    parm[@"pageNum"] = [NSNumber numberWithInteger:pageNum];
    parm[@"pageSize"] = [NSNumber numberWithInteger:pageSize];
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

-(NSURLSessionDataTask *)getUserInfo:(NSString *)userCode accessToken:(NSString *)accessToken url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (userCode && userCode.length) {
        parm[@"userCode"] = userCode;
    }
    if (accessToken && accessToken.length) {
        parm[@"accessToken"] = accessToken;
    }
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

-(NSURLSessionDataTask *)addItem:(NSString *)userCode accessToken:(NSString *)accessToken productNo:(NSString *)productNo url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (userCode && userCode.length) {
        parm[@"userCode"] = userCode;
    }
    if (accessToken && accessToken.length) {
        parm[@"accessToken"] = accessToken;
    }
    if (productNo && productNo.length) {
        parm[@"productNo"] = productNo;
    }
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

-(NSURLSessionDataTask *)changeItem:(NSString *)userCode accessToken:(NSString *)accessToken itemId:(NSInteger)itemId quantity:(NSInteger)quantity url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (userCode && userCode.length) {
        parm[@"userCode"] = userCode;
    }
    if (accessToken && accessToken.length) {
        parm[@"accessToken"] = accessToken;
    }
    parm[@"itemId"] = [NSNumber numberWithInteger:itemId];
    parm[@"quantity"] = [NSNumber numberWithInteger:quantity];
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

-(NSURLSessionDataTask *)delItem:(NSString *)userCode accessToken:(NSString *)accessToken itemId:(NSInteger)itemId url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (userCode && userCode.length) {
        parm[@"userCode"] = userCode;
    }
    if (accessToken && accessToken.length) {
        parm[@"accessToken"] = accessToken;
    }
    parm[@"itemId"] = [NSNumber numberWithInteger:itemId];
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

-(NSURLSessionDataTask *)createItemOrder:(NSString *)userCode accessToken:(NSString *)accessToken itemIds:(NSString *)itemIds orderAmount:(CGFloat)orderAmount remark:(NSString *)remark url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (userCode && userCode.length) {
        parm[@"userCode"] = userCode;
    }
    if (accessToken && accessToken.length) {
        parm[@"accessToken"] = accessToken;
    }
    if (itemIds && itemIds.length) {
        parm[@"itemIds"] = itemIds;
    }
    parm[@"orderAmount"] = [NSNumber numberWithFloat:orderAmount];
    if (remark && remark.length) {
        parm[@"remark"] = remark;
    }
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

-(NSURLSessionDataTask *)createOrder:(NSString *)userCode accessToken:(NSString *)accessToken productNo:(NSString *)productNo orderAmount:(CGFloat)orderAmount remark:(NSString *)remark url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (userCode && userCode.length) {
        parm[@"userCode"] = userCode;
    }
    if (accessToken && accessToken.length) {
        parm[@"accessToken"] = accessToken;
    }
    if (productNo && productNo.length) {
        parm[@"productNo"] = productNo;
    }
    parm[@"orderAmount"] = [NSNumber numberWithFloat:orderAmount];
    if (remark && remark.length) {
        parm[@"remark"] = remark;
    }
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

- (NSURLSessionDataTask *)createPointOrder:(NSString *)userCode accessToken:(NSString *)accessToken prodectNo:(NSString *)productNo point:(NSString *)point remark:(NSString *)remark url:(NSString *)url completionHnadle:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"userCode"] = userCode;
    params[@"accessToken"] = accessToken;
    params[@"productNo"] = productNo;
    params[@"points"] = point;
    params[@"remark"] = remark;
    return [self requestWithMethod:@"POST" path:url parameters:params completion:completionBlock];
}

-(NSURLSessionDataTask *)changeInfo:(NSString *)userCode accessToken:(NSString *)accessToken address:(NSString *)address url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (userCode && userCode.length) {
        parm[@"userCode"] = userCode;
    }
    if (accessToken && accessToken.length) {
        parm[@"accessToken"] = accessToken;
    }
    if (address && address.length) {
        parm[@"address"] = address;
    }
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

//申请提现审核   支付方式：0-银行卡    提现方式:0-现金提现；1-购车基金提现
-(NSURLSessionDataTask *)checkCash:(NSString *)userCode accessToken:(NSString *)accessToken amount:(NSString *)amount paymethod:(NSInteger)paymethod cashType:(NSInteger)cashType url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (userCode && userCode.length) {
        parm[@"userCode"] = userCode;
    }
    if (accessToken && accessToken.length) {
        parm[@"accessToken"] = accessToken;
    }
    if (amount && amount.length) {
        parm[@"amount"] = amount;
    }
    parm[@"paymethod"] = [NSNumber numberWithInteger:paymethod];
    parm[@"cashType"] = [NSNumber numberWithInteger:cashType];
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

-(NSURLSessionDataTask *)getExchangeRecord:(NSString *)userCode accessToken:(NSString *)accessToken type:(NSInteger)type pageNum:(NSInteger)pageNum pageSize:(NSInteger)pageSize url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (userCode && userCode.length) {
        parm[@"userCode"] = userCode;
    }
    if (accessToken && accessToken.length) {
        parm[@"accessToken"] = accessToken;
    }
    parm[@"type"] = [NSNumber numberWithInteger:type];
    parm[@"pageNum"] = [NSNumber numberWithInteger:pageNum];
    parm[@"pageSize"] = [NSNumber numberWithInteger:pageSize];
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

-(NSURLSessionDataTask *)getOrderData:(NSString *)userCode accessToken:(NSString *)accessToken pageNum:(NSInteger)pageNum pageSize:(NSInteger)pageSize url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (userCode && userCode.length) {
        parm[@"userCode"] = userCode;
    }
    if (accessToken && accessToken.length) {
        parm[@"accessToken"] = accessToken;
    }
    parm[@"pageNum"] = [NSNumber numberWithInteger:pageNum];
    parm[@"pageSize"] = [NSNumber numberWithInteger:pageSize];
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

//订单详情
-(NSURLSessionDataTask *)managerOrders:(NSString *)userCode accessToken:(NSString *)accessToken orderId:(NSInteger)orderId url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (userCode && userCode.length) {
        parm[@"userCode"] = userCode;
    }
    if (accessToken && accessToken.length) {
        parm[@"accessToken"] = accessToken;
    }
    parm[@"orderId"] = [NSNumber numberWithInteger:orderId];
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

-(NSURLSessionDataTask *)changeAccountInfo:(NSString *)userCode accessToken:(NSString *)accessToken bankHolder:(NSString *)bankHolder bankNumber:(NSString *)bankNumber bankName:(NSString *)bankName url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (userCode && userCode.length) {
        parm[@"userCode"] = userCode;
    }
    if (accessToken && accessToken.length) {
        parm[@"accessToken"] = accessToken;
    }
    if (bankHolder && bankHolder.length) {
        parm[@"bankHolder"] = bankHolder;
    }
    if (bankNumber && bankNumber.length) {
        parm[@"bankNumber"] = bankNumber;
    }
    if (bankName && bankName.length) {
        parm[@"bankName"] = bankName;
    }
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}

-(NSURLSessionDataTask *)changePsw:(NSString *)userCode accessToken:(NSString *)accessToken oldPsw:(NSString *)oldPsw newPsw:(NSString *)newPsw url:(NSString *)url completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (userCode && userCode.length) {
        parm[@"userCode"] = userCode;
    }
    if (accessToken && accessToken.length) {
        parm[@"accessToken"] = accessToken;
    }
    if (oldPsw && oldPsw.length) {
        parm[@"oldPsw"] = oldPsw;
    }
    if (newPsw && newPsw.length) {
        parm[@"newPsw"] = newPsw;
    }
    return [self requestWithMethod:@"POST" path:url parameters:parm completion:completionBlock];
}



#pragma mark - 基础方法
#pragma mark - Class Methods

+ (instancetype)sharedManager
{
    static dispatch_once_t onceQueue;
    static ToolNet *__sharedManager = nil;
    dispatch_once(&onceQueue, ^{
        __sharedManager = [[self alloc] init];
        
//        __sharedManager.status =AFNetworkReachabilityStatusReachableViaWiFi;
//        /**
//         AFNetworkReachabilityStatusUnknown          = -1,  // 未知
//         AFNetworkReachabilityStatusNotReachable     = 0,   // 无连接
//         AFNetworkReachabilityStatusReachableViaWWAN = 1,   // 3G 花钱
//         AFNetworkReachabilityStatusReachableViaWiFi = 2,   // 局域网络,不花钱
//         */
//        // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
//        [[AFNetworkReachabilityManager sharedManager] startMonitoring];
//        
//        // 检测网络连接的单例,网络变化时的回调方法
//        [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//            __sharedManager.status = status;
//        }];
    });
    return __sharedManager;
}

- (id)init
{
    self = [super initWithBaseURL:[[self class] APIBaseURL]];
    if (self)
    {
        self.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        self.requestSerializer.timeoutInterval = TIMEOUT_INTERVAL;
        AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
        [serializer setRemovesKeysWithNullValues:YES];
        self.responseSerializer = serializer;
        
//        NSString *baseurl = self.baseURL;
        
//        [self.requestSerializer setAuthorizationHeaderFieldWithUsername:@"d3ub5Uchuba28phavu32b62ratreveku" password:@"sawr5DEthaPHeyes"];
//        [self.requestSerializer setValue:@"Chat/2.6.1 CFNetwork/672.0.2 Darwin/14.0.0" forHTTPHeaderField:@"User-Agent"];
    }
    
    return self;
}

+ (NSURL *)APIBaseURL
{
    return [NSURL URLWithString:WEBSERVICEDOMAIN];
}


- (NSURLSessionDataTask *)requestWithMethod:(NSString *)method
                                       path:(NSString *)path
                                 parameters:(NSDictionary *)parameters
                                 completion:(NetResponseCompletionBlock)completion
{
    return [self requestWithMethod:method path:path parameters:parameters overlay:NO completion:completion commonSuccessHandler:nil commonErrorHandler:nil];
}


- (NSURLSessionDataTask *)requestWithMethod:(NSString *)method
                                       path:(NSString *)path
                                 parameters:(NSDictionary *)parameters
                                    overlay:(BOOL)overlay
                                 completion:(NetResponseCompletionBlock)completion
{
    return [self requestWithMethod:method path:path parameters:parameters overlay:overlay completion:completion commonSuccessHandler:nil commonErrorHandler:nil];
}


- (NSURLSessionDataTask *)requestWithMethod:(NSString *)method
                                       path:(NSString *)path
                                 parameters:(NSDictionary *)parameters
                                    overlay:(BOOL)overlay
                                 completion:(NetResponseCompletionBlock)completion
                       commonSuccessHandler:(NetResponseSuccessBlock)commonSuccessHandler
                         commonErrorHandler:(CommonBlock)commonErrorHandler
{
    
    return [self requestWithMethod:method path:path parameters:parameters overlay:overlay overlayBaseView:mAppDelegate.window.rootViewController.view
                        completion:completion commonSuccessHandler:commonSuccessHandler commonErrorHandler:commonErrorHandler];
}


- (NSURLSessionDataTask *)requestWithMethod:(NSString *)method
                                       path:(NSString *)path
                                 parameters:(NSDictionary *)parameters
                                    overlay:(BOOL)overlay
                      overlayBaseView:(UIView*)overlayBaseView
                                 completion:(NetResponseCompletionBlock)completion
                       commonSuccessHandler:(NetResponseSuccessBlock)commonSuccessHandler
                         commonErrorHandler:(CommonBlock)commonErrorHandler
{
    NSString *URLString = [[NSURL URLWithString:path relativeToURL:self.baseURL] absoluteString];
    
    NSError *error;
    //错误类型主要是：断网、取消访问、访问超时
    //所有错误消息的处理都放在这里，外部无需处理错误消息
    
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:URLString parameters:parameters error:&error];
    
    [request setValue:@"AZKJ(iPhone)" forHTTPHeaderField:@"User-Agent"];
    MRProgressOverlayView *overlayView = nil;
    
    if (overlay && overlayBaseView) {
        
        overlayView = [MRProgressOverlayView showOverlayAddedTo:overlayBaseView  title:@"" mode:MRProgressOverlayViewModeIndeterminateSmallDefault  animated:YES];
        [overlayView setTintColor:UIResourceMainColor];
    }
    NSLog(@"Request: %@", request);

    NSURLSessionDataTask *task = [self dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (overlayView) {
            [overlayView dismiss:YES];
        }
        if (error) {
            NSString *errMsg = error.localizedDescription;
            switch (error.code) {
                case NSURLErrorCancelled:
                    errMsg = nil;
                    break;
                    
                case NSURLErrorCannotFindHost:
                    errMsg = @"十有八九断网啦，赶紧去设置看下吧！";
                    break;
                    
                case NSURLErrorTimedOut://请求超时
                    errMsg = @"颜值太低，访问超时！";
                    break;
                    
                default:
                    break;
            }
            if (errMsg) {
                [TSMessage showMessage:errMsg type:TSMessageNotificationTypeError];
            }
            if (commonErrorHandler) {
                commonErrorHandler();
            }
            else {
                if (completion) {
                    completion(nil, nil, error);
                }
            }
            return;
        }
        else {
            //当请求成功后调用如下代码, 保存Cookie
            NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL: [NSURL URLWithString:WEBSERVICEDOMAIN]];
            NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cookies];
            [mUserDefaults app_setCookie:data];
            
            if (commonSuccessHandler) {
                commonSuccessHandler(responseObject);
            }
            else {
                if (completion) {
                    completion(nil, responseObject, error);
                }
            }
        }
    }];
    
    [task resume];
    
    if (overlay) {
        [overlayView setStopBlockForTask:task];
    }
    
    return task;
}

-(NSURLSessionDataTask *)login:(NSString *)mobile password:(NSString *)password overlayBaseView:(UIView*)overlayBaseView completionHandler:(NetResponseCompletionBlock)completionBlock
{
    NetResponseSuccessBlock commonSuccessHandler = ^(NSDictionary* responseJson){
        
        if ([responseJson[@"status"] isEqual:@1]) {
            [mUserDefaults app_setUserInfo:responseJson];
        }
        if (completionBlock) {
            completionBlock(nil, responseJson, nil);
        }
    };
    
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (mobile && mobile.length) {
        parm[@"mobile"] = mobile;
    }
    if (password && password.length) {
        parm[@"password"] = password;
    }
    return [self requestWithMethod:@"POST"
                              path:MLoginCheck
                        parameters:parm
                           overlay:YES
                   overlayBaseView:overlayBaseView
                        completion:completionBlock
              commonSuccessHandler:commonSuccessHandler
                commonErrorHandler:nil];
}

-(NSURLSessionDataTask *)oauthLogin:(NSString *)type openid:(NSString *)openid accessToken:(NSString *)accessToken device:(NSString *)device deviceid:(NSString *)deviceid overlayBaseView:(UIView*)overlayBaseView completionHandler:(NetResponseCompletionBlock)completionBlock;
{
    NetResponseSuccessBlock commonSuccessHandler = ^(NSDictionary* responseJson){
        
        if ([responseJson[@"status"] isEqual: @1]) {
            [mUserDefaults app_setUserInfo:responseJson];
        }
        if (completionBlock) {
            completionBlock(nil, responseJson, nil);
        }
    };
    
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    if (type && type.length) {
        parm[@"type"] = type;
    }
    if (openid && openid.length) {
        parm[@"openid"] = openid;
    }
    if (accessToken && accessToken.length) {
        parm[@"accessToken"] = accessToken;
    }
    if (device && device.length) {
        parm[@"device"] = device;
    }
    if (deviceid && deviceid.length) {
        parm[@"deviceid"] = deviceid;
    }
    
    return [self requestWithMethod:@"POST"
                              path:nil
                        parameters:parm
                           overlay:YES
                   overlayBaseView:overlayBaseView
                        completion:completionBlock
              commonSuccessHandler:commonSuccessHandler
                commonErrorHandler:nil];
}

-(void)uploadImage:(UIImage *)image completionHandler:(NetFileUploadCompletionBlock)completionBlock
{
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:WEBSERVICEDOMAIN]];
    
    NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
    
    [manager POST:MUploadImage parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"img" fileName:@"img.jpg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"Success: %@ ***** %@", task.response, responseObject);
        completionBlock(responseObject, responseObject, nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error: %@ ***** %@", task.response, error);
        completionBlock(nil, nil, error);
    }];
}

- (void)uploadSingImage:(UIImage *)signImage userCode:(NSString *)userCode paraentVC:( UIViewController *)paraentVc completionHandler:(NetFileUploadCompletionBlock)completionBlock
{
    MRProgressOverlayView *overlayView = [MRProgressOverlayView showOverlayAddedTo:paraentVc.view title:@"上传中..." mode:MRProgressOverlayViewModeIndeterminateSmallDefault animated:YES];
    [overlayView setTintColor:UIResourceMainColor];
    
    if ([[AFNetworkReachabilityManager sharedManager] isReachable])
    {
        [self uploadImage:signImage completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            if ([responseObject[@"code"] isEqual:@1]) {
                NSMutableDictionary * params = [NSMutableDictionary dictionary];
                params[@"userCode"] = userCode; //@"1505439251548004";
                params[@"singImg"] = responseObject[@"data"];
                AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:WEBSERVICEDOMAIN]];
                [manager POST:MUPloadSingImg parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    [overlayView dismiss:YES];
                    NSLog(@"Success: %@ ***** %@", task.response, responseObject);
                    completionBlock(responseObject, responseObject, nil);
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    NSLog(@"Error: %@ ***** %@", task.response, error);
                    completionBlock(nil, nil, error);
                }];
            }else {
                [TSMessage showMessage:@"签名上传失败" type:TSMessageNotificationTypeError];
            }
        }];
    }
}

-(void)uploadFile:(NSString *)filePath token:(NSString *)token completionHandler:(NetFileUploadCompletionBlock)completionBlock
{
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:WEBSERVICEDOMAIN]];
    
    [manager POST:[MUploadAudio stringByAppendingString:token] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:filePath] name:@"video" fileName:[filePath lastPathComponent] mimeType:@"audio/mp3" error:nil];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        float progress = 1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
        NSLog(@"上传进度 ----- %f",progress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"上传成功 %@",responseObject);
        completionBlock(responseObject, responseObject, nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传失败 %@",error);
        completionBlock(nil, nil, error);
    }];
}

-(void)downloadFile:(NSString *)urlStr
                          destination:(NSString *)destination
                       completionHandler:(NetFileDownloadCompletionBlock)completionBlock
{
    if ([[NSFileManager defaultManager] fileExistsAtPath:destination])
    {
        completionBlock(nil, [NSURL fileURLWithPath: destination], nil);
        return;
    }
    
    NSURL *URL = [NSURL URLWithString:urlStr];
    if ([urlStr hasPrefix:@"http://"] || [urlStr hasPrefix:@"https://"]) {
        URL = [NSURL URLWithString:urlStr];
    }
    else{
        URL = [NSURL URLWithString:urlStr relativeToURL:WEBSERVICEDOMAIN];
    }
    
    MRProgressOverlayView *overlayView = [MRProgressOverlayView showOverlayAddedTo:mAppDelegate.window.rootViewController.view title:@"下载中..." mode:MRProgressOverlayViewModeDeterminateCircular  animated:YES];
    [overlayView setTintColor:UIResourceMainColor];

    NSURLRequest *request = [NSURLRequest requestWithURL:URL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:600];
    
    NSURLSessionDownloadTask *downloadTask =
    [self downloadTaskWithRequest:request
                         progress:nil
                      destination:^NSURL *(NSURL *targetPath, NSURLResponse *response)
                                    {
                                        return [NSURL fileURLWithPath:destination];
                                    }
                completionHandler:completionBlock];
    
    [downloadTask resume];
    [overlayView setModeAndProgressWithStateOfTask:downloadTask];
    [overlayView setStopBlockForTask:downloadTask];
}



@end
